import { defineComponent, reactive, ref, toRaw } from 'vue';
import './index.less';
import setting from '/@/settings/projectSetting';
import { useGo } from '/@/hooks/web/usePage';
import { useRouter } from 'vue-router';
import { useMessage } from '/@/hooks/web/useMessage';
import type { CardDetail } from '/@/api/gateruler/model/cardModel';
import { aTabClick, awaitWrap } from '/@/utils';
import { CardDetailApi } from '/@/api/gateruler/card';
import Title from '/@/views/gateruler/components/Title';
import { cloneDeep, find } from 'lodash-es';
import { Skeleton, Rate, Button, ConfigProvider } from 'vant';
import { Icon } from '/@/components/Icon';
import { appShareUsing } from '/@/utils/appInteractive';
import ClipboardJS from 'clipboard';
import { WeChatUrlApi } from '/@/api/common';
import { GameIdEnum } from '/@/api/model/commonModel';
import { useOptions } from '/@/views/gateruler/hooks/useOptions';
import MoreVersionPopup from './components/MoreVersionPopup';

export default defineComponent({
  name: 'GateRuleCardDetailPage',
  props: {
    id: {
      type: String as PropType<string>,
      required: true,
    },
  },
  setup(props) {
    // 设置分享参数
    appShareUsing({
      title: '',
      content: '',
      image: '',
      url: window.location.href,
    });

    const go = useGo();
    const router = useRouter();
    const { createSuccessToast, createFailToast } = useMessage();
    const { rarityOptions } = useOptions();

    const cardDetailInfo = reactive<CardDetail>({} as CardDetail);

    const loadingState = ref(true);
    const getDetail = async (card_id: number) => {
      const [error, data] = await awaitWrap(CardDetailApi({ card_id: card_id }));
      if (error) {
        return false;
      }
      const result = data as CardDetail;
      for (const item in result) {
        cardDetailInfo[item] = result[item];
      }
      loadingState.value = false;
    };
    getDetail(Number(props.id));
    const FirstBox = () => {
      // 稀有度
      let RarityHtml: VueNode = <span></span>;
      if (cardDetailInfo.rarity > 0) {
        RarityHtml = <Rate v-model={[cardDetailInfo.rarity]} count={cardDetailInfo.rarity} color={'#000'} />;
      } else {
        const target = find(rarityOptions, ['value', cardDetailInfo.rarity]);
        RarityHtml = <span>{target ? target.label : '-'}</span>;
      }

      // 能力
      const abilityArr = cardDetailInfo.ability ? cardDetailInfo.ability.split(',') : [];
      const abilityHtml: VueNode[] = [];
      if (abilityArr.length > 0) {
        abilityArr.map((item) => {
          abilityHtml.push(<span>{item}</span>);
        });
      }

      // 属性
      const attrArr = cardDetailInfo.attrs ? cardDetailInfo.attrs.split(',') : [];
      const attrHtml: VueNode[] = [];
      if (attrArr.length > 0) {
        attrArr.map((item) => {
          attrHtml.push(<span>{item}</span>);
        });
      }

      // 复制牌名
      // const { copy } = useClipboard();
      const copyName = () => {
        /*copy(cardDetailInfo.name)
          .then(() => {
            createSuccessToast({
              message: '复制牌名成功',
            });
          })
          .catch(() => {
            createFailToast({
              message: '复制牌名失败',
            });
          });*/
        const clipboard = new ClipboardJS('.copy-card-name', {
          text: function () {
            return cardDetailInfo.name;
          },
        });
        clipboard.on('success', function () {
          createSuccessToast({
            message: '复制牌名成功',
          });
        });
        clipboard.on('error', function () {
          createFailToast({
            message: '复制牌名失败',
          });
        });
      };

      // 其他版本
      let otherVersionHtml: VueNode = null;
      if (cardDetailInfo.other_version.length) {
        const versionData = cloneDeep(cardDetailInfo.other_version);
        const versionArr = versionData.length > 2 ? versionData.slice(0, 2) : versionData;
        otherVersionHtml = (
          <div class={'other-version'}>
            <div class={'other-tile flex justify-between'}>
              <span>其他版本</span>
              <span
                onClick={() => {
                  moreVerState.value = true;
                }}
              >
                查看更多
              </span>
            </div>
            <ul class={'ver-list'}>
              {versionArr.map((item) => {
                return (
                  <li class={'text-xs text-blue-400'}>
                    <span
                      onClick={() => {
                        go(`/gaterulercard/${item.card_id}`);
                      }}
                    >
                      {item.series_name} {item.card_no}
                    </span>
                  </li>
                );
              })}
            </ul>
          </div>
        );
      }

      return (
        <div class={'first-box relative'}>
          <div class={'flex relative'}>
            <div class={'image'}>
              <img src={cardDetailInfo.img} alt='' />
            </div>
            <ul class={'info'}>
              <li class={'card-title flex justify-between items-start'}>
                <h1 class={'card-name'}>{cardDetailInfo.name}</h1>
                <div class={'foil'}>
                  <img
                    src={`${setting.imgUrlCdn}card-tools/yingdiimg/gateruler/card/${
                      cardDetailInfo.is_foil ? 'flash' : 'flat'
                    }.png`}
                    alt=''
                  />
                </div>
              </li>
              <li class={'card-subtitle text-gray-400 van-ellipsis'}>{cardDetailInfo.ename}</li>
              <li class={'card-series van-ellipsis text-gray-400'}>
                <span>{cardDetailInfo.series_name}</span>
              </li>
              <li class={'card-card-no van-ellipsis text-gray-400'}>
                <span> {cardDetailInfo.card_no}</span>
              </li>
              <li class={'card-rarity flex items-center justify-between'}>
                <div class={'star'}>
                  {RarityHtml}
                  <span class={'clazz'}>{cardDetailInfo.card_class}</span>
                </div>
                <span class={'category'}>{cardDetailInfo.card_category}</span>
              </li>
              <li class={`card-ability flex ${!abilityArr.length ? 'hidden' : ''}`}>{abilityHtml}</li>
              <li class={'card-attrs flex'}>{attrHtml}</li>
              <ConfigProvider
                class={'copy-box absolute'}
                themeVars={{
                  buttonBorderWidth: 0,
                  buttonDefaultColor: '#1380F0',
                  buttonDefaultBackground: '#DBEDFF',
                  buttonRadius: '20px',
                }}
              >
                <li class={'card-evo flex justify-between'}>
                  <Button size={'mini'} onClick={copyName} class={'copy-card-name'}>
                    点击复制牌名
                  </Button>
                </li>
              </ConfigProvider>
            </ul>
          </div>
          <div class='van-hairline--top !mb-0' />
          {otherVersionHtml}
        </div>
      );
    };
    const LastBox = () => {
      if (!cardDetailInfo.rule && !cardDetailInfo.description) {
        return null;
      }
      return (
        <div class={'last-box'}>
          <p class='rule text-sm whitespace-pre-line'>{cardDetailInfo.rule}</p>
          <p class='description text-sm text-gray-400 whitespace-pre-line'>{cardDetailInfo.description}</p>
          <ul class={'artist-box pt-md mt-md'}>
            <li class={'text-sm'}>
              <span>画 家</span>：{cardDetailInfo.artist || '无'}
            </li>
            <li class={'text-sm'}>
              <span>军 团</span>：{cardDetailInfo.legion || '无'}
            </li>
          </ul>
        </div>
      );
    };

    // 更多版本浮层
    const moreVerState = ref(false);

    // 跳转到小程序
    const weChatClick = async () => {
      const { id } = props;
      const [error, data] = await awaitWrap(WeChatUrlApi({ game_id: GameIdEnum.GATERULER, card_id: Number(id) }));
      if (error || !data) {
        aTabClick(setting.wechatAppHomeUrl, '_blank');
        return;
      }
      aTabClick(data, '_blank');
    };

    return () => (
      <div class={'card-detail-container'}>
        <Title
          title={cardDetailInfo.name}
          leftArrow={true}
          onLeftClick={() => {
            router.go(-1);
          }}
        />
        <Skeleton title row={5} avatar loading={loadingState.value}>
          <div class={'detail-box'}>
            <FirstBox />
            <LastBox />
          </div>
        </Skeleton>
        <div class={'mall flex justify-center'}>
          {Number(cardDetailInfo.min_price) ? (
            <ul class={'price flex items-center'}>
              <li>最低价</li>
              <li class={'nums'}>
                <span>¥</span>
                {cardDetailInfo.min_price}
              </li>
            </ul>
          ) : null}
          <div class={'shop-car text-base text-blue-500 flex items-center'} onClick={weChatClick}>
            <Icon class={'!text-lg'} icon={'material-symbols:shopping-cart-rounded'} />
            <span>前去购买</span>
          </div>
        </div>
        <MoreVersionPopup v-model={[moreVerState.value, 'show']} cardDetail={toRaw(cardDetailInfo)} />
      </div>
    );
  },
});
